package cc.openkit.kitwebapi.controller;

import cc.openkit.exception.MyException;
import cc.openkit.kitmodel.demo.Demo;
import cc.openkit.kitservice.demo.DemoService;
import cc.openkit.result.Result;
import cc.openkit.result.ResultEnum;
import cc.openkit.result.ResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPool;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/test")
public class DemoController {

    @Autowired
    private DemoService demoService;

    @Autowired
    JedisPool jedisPool;

    @GetMapping("add")
    private Object add(int id, String name){

        Demo demo = new Demo();
        demo.setUsername(name);
        demo.setId(id);
        demo.setNickname("ben");
        demo.setPassword("123123");
        demo.setUpdateTime(new Date());

//        return demoService.addOne(demo);

        Map<String,Object> retMap = new HashMap<>();
        retMap.put("demo",demo);
        return null;
    }

    /**
     * 各种异常测试
     * @return
     * @throws Exception
     */
    @RequestMapping("/exception")
    public Result exception(String name, String pwd) throws Exception {
        String realname="tiankonglanlande";
        String realPwd="123";
        if(null!=name&&name.equals("xx")){
            throw new Exception("系统异常！");
        }

        if(StringUtils.isEmpty(name)||StringUtils.isEmpty(pwd)){
            throw new MyException("参数必须传111！");
        }else if (!name.equals(realname)||!pwd.equals(realPwd)){
            throw new MyException("用户名或密码不正确！");
        }

        String info="你好["+name+"]!";
        return ResultUtils.success(info);
    }

    /**
     * 测试未登录异常
     * @return
     * @throws Exception
     */
    @RequestMapping("/unlogin")
    public Result unlogin() throws Exception {
        return ResultUtils.success(ResultEnum.UNLOGIN);
    }

    /**
     * 测试自定义异常
     * @return
     * @throws Exception
     */
    @RequestMapping("/success")
    public Result success() throws Exception {
        jedisPool.getResource().set("Hello","HelloWorld");
//        srt.opsForValue().set("USER-TOKEN:11111", "ASDASDSA", 1, TimeUnit.HOURS);
        String token = "11111";
        // TODO 存储到对应的redis
        jedisPool.getResource().set("USER-TOKEN:"+token, "ASDASDSA");   // 将数据存到redis
        // TODO 根据前端传来的 token 去 redis 获取对应的 详细信息
        String s = jedisPool.getResource().get("USER-TOKEN:" + token);
        System.out.println(s);
        return ResultUtils.success(200,"自定义消息");
    }

}
